<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入职工姓名"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe @expand-change="handleExpand">
        <!-- 展开区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">

            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in userRoleList[scope.row.id][0]" :key="item1">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag >{{item1}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row :class="[ 'vcenter']" >
                  <el-col :span="6" v-for="(item2, i2) in userRoleList[scope.row.id][1][i1]" :key="item2.id">
                    <el-tag type="success" closable @close="removeRoleById(scope.row, item2.id)">{{item2.role_name}}</el-tag>
                    
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="name">
        </el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <!-- <el-table-column label="" prop="role"></el-table-column> -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_active"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogVisible"
    >
      <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="formData"
        size="medium"
        label-width="100px"
      >
        <el-col :span="24">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号"
              :maxlength="11"
              show-word-limit
              clearable
              prefix-icon="el-icon-mobile"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
              :maxlength="30"
              show-word-limit
              clearable
              prefix-icon="el-icon-s-promotion"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入姓名"
              :maxlength="4"
              show-word-limit
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-form>
      </el-row>
    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAdminuser">确 定</el-button>
      </span>
    </el-dialog>

    

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetAdminUser,
  removeAdminUser,
  updateAdminUserState,
  updateAdminuserInfo,
  DeleteAdminUserInfo,
  getAdminuserById
} from '@/api/adminuser'
import { getFilterRoleList,getAllRole,editRoleItem } from '../../api/role'
export default {
  data() {
    return {
       formData: {
        phone: '',
        email: '',
        name: '',
      },
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      userlist: [],
      total: 0,
      departmentList:[],
      roleList:[],
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      //存储每个用户的部门和角色信息 
      //让用户id作为键
      userRoleList:{},
      // 已选中的角色Id值
      selectedRoleId: '',
      setRoleDialogVisible:false,
      editDialogVisible:false,
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const result = await GetAdminUser(this.queryInfo)
      this.userlist = result.data
      this.total = result.count //数据总条数
      result.data.forEach(item=>{
        this.$set(this.userRoleList,item.id,[[],[]])
      })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      const result = await updateAdminUserState(userinfo)
      if(result!=undefined){
        this.$message.success('更新用户状态成功！')
      }
    },
    //监听 展开项
    async handleExpand(row){
      const roles=await getFilterRoleList('role_ids',JSON.stringify(row.role))
      const departmentList=[]
      const roleList=[]
      roles.forEach(item => {
        if(!departmentList.includes(item.department)){
          departmentList.push(item.department)
          //筛选这个部门对应的角色信息
          let departRole=roles.filter(role=>role.department==item.department)
          roleList.push(departRole)
        } 
      });
      const userRoles=[departmentList,roleList]
      this.$set(this.userRoleList,row.id,userRoles)

      this.departmentList=departmentList
      this.roleList=roleList

    },
    //删除用户职位信息
    removeRoleById(row,role_id){
      row.role.forEach((item)=>{
        if (role_id==item){
          const result = DeleteAdminUserInfo(role_id)
          
        }
      })
      this.getUserList()
      
    },
    
    // 展示编辑用户的对话框
    async showEditDialog(userInfo) {
      this.userInfo=userInfo
      this.editDialogVisible = true
      const res  = await getAdminuserById(this.userInfo.id)
      // console.log(res,'res')
      // if (res.meta.status !== 200) {
      //   return this.$message.error('查询用户信息失败！')
      // }
      this.formData = res
    },
    
    // 根据Id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const result = await removeAdminUser(id)
      if (result != undefined) {
        this.$message.success('删除用户成功！')
        this.getUserList()
      }
    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      console.log(userInfo)
      this.setRoleDialogVisible = true
      // 在展示对话框之前，获取所有角色的列表
      const res = await getAllRole()
      console.log(res.data)
      // if (res.meta.status !== 200) {
      //   return this.$message.error('获取角色列表失败！')
      // }
      var array=res.data
      array.forEach(item=>{
        item.role_name=item.role_name+'('+item.department+')'
      })
      userInfo.role.forEach(item1=>{
          var aa=''
          array.forEach(item=>{
            if (item.id==item1){
              aa+=item.role_name
            }
            
          })
          userInfo.role_name=aa 
        })
      this.rolesList = array


    },
    // 修改信息功能
    async editAdminuser(){
      console.log(123)
      this.editDialogVisible = false
      var res = await updateAdminuserInfo(this.userInfo.id,this.formData)
      this.getUserList()
      // console.log(res,'res')
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }

      const res = await updateAdminuserInfo(this.userInfo.id,{role:[this.selectedRoleId]})
      // console.log(res)
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    },
  },
}
</script>

<style  scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
